package cn.com.lms.app.api.exam;


import cn.com.lms.app.api.exam.vo.*;
import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.enums.SubjectTypeEnum;
import cn.com.lms.business.exam.persistence.entity.*;
import cn.com.lms.business.exam.service.*;
import cn.com.lms.business.exam.utils.BeanListUtils;
import cn.com.lms.business.exam.utils.JsonUtil;
import cn.com.lms.business.user.persistence.entity.SysUserVo;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;

import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author zhangzhenjiang
 * @createDate 2020/3/20
 * @description
 */
@Tag(name = "练习", description = "题库练习管理")
@RestController
@RequestMapping("/app/api/exam")
public class ExerciseApi {

    @Autowired
    EmployeeExerciseSubjectService employeeExerciseSubjectService;

    @Autowired
    ExerciseService exerciseService;

    @Autowired
    QuestionSubjectService questionSubjectService;


    @Autowired
    QuestionSubjectFileService questionSubjectFileService;

    @Autowired
    QuestionSubjectOptionService questionSubjectOptionService;
    @Autowired
    QuestionSubjectAnswerService questionSubjectAnswerService;


    @Operation(summary = "练习分页查询", description = "查询练习的题目列表",
            parameters = {
                    @Parameter(name = "userId", description = "用户ID", allowEmptyValue = true,
                            allowReserved = true, schema = @Schema(implementation = Long.class, description = "userId")),
                    @Parameter(name = "limit", description = "分页大小", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
                    @Parameter(name = "offset", description = "页码", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "页码")),
            })
    @GetMapping(value = "/exercise/page")
    public ResponseResult<Page<UserExerciseVO>> getExercisePage(HttpServletRequest request) {
        Long userId = request.getParameter("userId") != null ? Long.parseLong(request.getParameter("userId")) : 10000000L;
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        if (sysUser != null) {
            userId = sysUser.getId();
        }
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "ex.create_time"));
        QueryHelpBean queryHelpBean = ExerciseService.getUserExerciseQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        //试卷名称，模糊搜索
        IExpression andCondition1 = CompareExpression.build("ex.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(andCondition1);

        IExpression andCondition3 = CompareExpression.build("ex.is_enable", CompareType.equal, true);
        queryHelpBean.addWhere(andCondition3);

        if (userId != null) {
            IExpression andCondition2 = CompareExpression.build("em.employee_id", CompareType.equal, userId);
            queryHelpBean.addWhere(andCondition2);
        }
        Page<UserExerciseVO> all = exerciseService.findAll(queryHelpBean);
        return ResponseResult.success(all);
    }

    @Operation(summary = "提交练习", description = "提交练习")
    @PostMapping("/exercise/subject/save")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<EmployeeExerciseSubject> addEmployeeExerciseSubject(@RequestBody EmployeeExerciseSubject employeeExerciseSubject) {
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        if (sysUser != null) {
            employeeExerciseSubject.setEmployeeId(sysUser.getId());
        } else {
            employeeExerciseSubject.setEmployeeId(10000000L);
        }

        employeeExerciseSubject.setCreateTime(new Date());
        EmployeeExerciseSubject result = employeeExerciseSubjectService.save(employeeExerciseSubject);
        return ResponseResult.success(result);
    }


    @Operation(summary = "题目分页查询", description = "查询练习的题目列表",
            parameters = {
                    @Parameter(name = "exerciseId", description = "练习ID", allowEmptyValue = false,
                            allowReserved = true, schema = @Schema(implementation = Long.class, description = "exerciseId")),
                    @Parameter(name = "limit", description = "分页大小", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "分页大小")),
                    @Parameter(name = "offset", description = "页码", allowEmptyValue = true, allowReserved = true, schema = @Schema(type = "int", description = "页码")),
            })
    @GetMapping(value = "/exercise/subject/page")
    public ResponseResult<Page<ExerciseSubjectVO>> getQuestionSubjectPage(HttpServletRequest request) {
        Long exerciseId = StringHelper.isNotEmpty(request.getParameter("exerciseId")) ? Long.parseLong(request.getParameter("exerciseId")) : null;

        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "qs.create_time"));
        QueryHelpBean queryHelpBean = questionSubjectService.getExciseSubjectQueryHelpBean(exerciseId);
        queryHelpBean.setPageable(pageable);
        Page<ExerciseSubjectVO> all = questionSubjectService.findAll(queryHelpBean);
        all.stream().forEach(exerciseSubjectVO -> {
            if (SubjectTypeEnum.JUDGE.getValue().equals(exerciseSubjectVO.getType())) {
                //根据试题ID,查询判断题答案
                exerciseSubjectVO.setOptions("A 正确###B 错误");
                if (exerciseSubjectVO.getAnswer().equals("false") || exerciseSubjectVO.getAnswer().equals("正确")) {
                    exerciseSubjectVO.setAnswer("A");
                }
                if (exerciseSubjectVO.getAnswer().equals("true") || exerciseSubjectVO.getAnswer().equals("错误")) {
                    exerciseSubjectVO.setAnswer("B");
                }
            }

        });

        return ResponseResult.success(all);
    }


    @Operation(summary = "根据id查询", description = "练习详情")
    @GetMapping("/exercise/detail/{id}")
    public ResponseResult<UserExerciseDetailVO> getUserExerciseDetailById(HttpServletRequest request, @Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<Exercise> exerciseOpt = exerciseService.findById(id);
        if (!exerciseOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Exercise exercise = exerciseOpt.get();
        UserExerciseDetailVO exerciseDetailVO = new UserExerciseDetailVO();
        BeanUtils.copyProperties(exercise, exerciseDetailVO);

        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        Long employeeId =sysUser.getId();

        List<Map<String, Object>> mapList = questionSubjectService.findExerciseQuestionSubjectVO(exercise.getId());
        List<ExerciseQuestionSubjectVO> exerciseQuestionSubjectVOList = new CopyOnWriteArrayList<>();
        List<SubjectAnswerVO> subjectAnswerVOList = new CopyOnWriteArrayList<>();
        if (!CollectionUtils.isEmpty(mapList)) {
            exerciseQuestionSubjectVOList = BeanListUtils.mapListToObjectList(mapList, ExerciseQuestionSubjectVO.class);
            subjectAnswerVOList = BeanListUtils.mapListToObjectList(mapList, SubjectAnswerVO.class);

              exerciseQuestionSubjectVOList.stream().filter(m->SubjectTypeEnum.JUDGE.getValue().intValue() == m.getType().intValue()).forEach(exerciseQuestionSubjectVO -> {
                                  exerciseQuestionSubjectVO.setOptions("A 正确###B 错误");
            });
        }
        exerciseDetailVO.setExerciseQuestionSubjectVOList(exerciseQuestionSubjectVOList);
        exerciseDetailVO.setSubjectAnswerVOList(subjectAnswerVOList);

        List<Map<String, Object>> employeeExerciseSubjectMapList = employeeExerciseSubjectService.findEmployeeExerciseSubjectByExerciseId(exercise.getId(), employeeId);
        List<UserSubjectAnswerVO> userSubjectAnswerVOList = new CopyOnWriteArrayList<>();
        if (!CollectionUtils.isEmpty(employeeExerciseSubjectMapList)) {
            userSubjectAnswerVOList = BeanListUtils.mapListToObjectList(employeeExerciseSubjectMapList, UserSubjectAnswerVO.class);
            userSubjectAnswerVOList.stream().forEach(userSubjectAnswerVO -> {
                if (userSubjectAnswerVO.getAnswer().equals("false") || userSubjectAnswerVO.getAnswer().equals("正确")) {
                    userSubjectAnswerVO.setAnswer("A");
                }
                if (userSubjectAnswerVO.getAnswer().equals("true") || userSubjectAnswerVO.getAnswer().equals("错误")) {
                    userSubjectAnswerVO.setAnswer("B");
                }
            });
        }
        exerciseDetailVO.setUserSubjectAnswerVOList(userSubjectAnswerVOList);

        return ResponseResult.success(exerciseDetailVO);
    }
}
